package com.swgk.core.view.weiget;

import android.content.Context;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ScaleXSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.OnLifecycleEvent;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.swgk.core.FragmentLifeCycle;
import com.swgk.core.R;
import com.swgk.core.base.AppFragment;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.ACAdminDialogUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.swgk.core.view.fragment.SimpleCardFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class BigHomeComparyWidget {

    private Context mContext;
    private AppFragment appFragment;
    //        private int[] mIconUnselectIds = {
//            R.mipmap.tab_home_unselect, R.mipmap.tab_speech_unselect,
//            R.mipmap.tab_contact_unselect, R.mipmap.tab_more_unselect};
//    private int[] mIconSelectIds = {
//            R.mipmap.tab_home_select, R.mipmap.tab_speech_select,
//            R.mipmap.tab_contact_select, R.mipmap.tab_more_select};
    LinearLayout inflatedCompany;
    FragmentManager fragmentManager;
    private int indexSelect = 0;
    private ArrayList<SimpleCardFragment> mFragments = new ArrayList<>();

    private int loadingTime = 4000;
    private TabLayout mCompanyTab;
    private Disposable disposable;
    private boolean isAotu = true; //是否自动
    private boolean iscontinue = true; //是否需要暂停
    private boolean isInIt = false;

    private boolean aotuTab;
    private boolean aotuContext;
    private ViewPager vp;
    private MutableLiveData<Boolean> mutableLiveData = new MutableLiveData<>();


    public BigHomeComparyWidget(AppFragment appFragment, LinearLayout inflatedCompany) {
        this.inflatedCompany = inflatedCompany;
        this.mContext = appFragment.getContext();
        this.appFragment = appFragment;
        this.fragmentManager = appFragment.getChildFragmentManager();
        addObserver(appFragment);
        LinearLayout btnComConfig = inflatedCompany.findViewById(R.id.btn_com_config);
        btnComConfig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityJump.startActivity(AppRouteConstant.EnterpriseConfigActivity);
                //showCompanyConfigWindow();
            }
        });
    }

    /**
     * 添加和当前Fragment的生命周期绑定
     *
     * @param appFragment
     */
    private void addObserver(AppFragment appFragment) {
        appFragment.setFragmentLifeCycle(new FragmentLifeCycle() {
            @Override
            public void onFragmentHiddenChanged(boolean hidden) {
                if (!isInIt) return;
                MLog.d("时间到 onFragmentHiddenChanged ");
                if (appFragment != null && appFragment.isVisible()) {
                    if (!hidden) {
                        stopTimer();
                    } else {
                        startTimer();
                    }
                }
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
            void onResume(LifecycleOwner owner) {
                if (!isInIt) return;
                MLog.d("时间到 onResume ");
                if (appFragment != null && appFragment.isVisible()) {
                    startTimer();
                }
            }

            @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
            void onPause(LifecycleOwner owner) {
                if (!isInIt) return;
                MLog.d("时间到 onPause ");
                if (appFragment != null && appFragment.isVisible()) {
                    stopTimer();
                }
            }
        });

        mutableLiveData.observe(appFragment.getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (appFragment != null && appFragment.isVisible()) {
                    setTimeType(aBoolean);
                }
            }
        });
    }


    public void unInit() {
        isInIt = false;
        stopTimer();
        if (vp != null) {
            vp.setAdapter(new MyPagerAdapter(fragmentManager, new ArrayList<>(), new ArrayList<>()));
        }
        mFragments.clear();
        if (mCompanyTab != null) {
            mCompanyTab.clearOnTabSelectedListeners();
            mCompanyTab.removeAllTabs();
        }
        indexSelect = 0;
    }

    public void initData(List<EnterpriseEditEntity> enterpriseEditEntity) {
        try{
            if (mCompanyTab == null) {
                mCompanyTab = inflatedCompany.findViewById(R.id.tl_company_title);
                vp = inflatedCompany.findViewById(R.id.view_page);
            }

            for (int i = 0; i < enterpriseEditEntity.size(); i++) {
                EnterpriseEditEntity data = enterpriseEditEntity.get(i);
                if (data != null && !TextUtils.isEmpty(data.getName())){
                    mFragments.add(SimpleCardFragment.getInstance(data,mutableLiveData));
                }
            }
            if (mFragments ==null || mFragments .size() == 0) return;
            MyPagerAdapter mAdapter = new MyPagerAdapter(fragmentManager,mFragments, enterpriseEditEntity);
            vp.setAdapter(mAdapter);
            vp.setOffscreenPageLimit(mFragments.size());
            mCompanyTab.setupWithViewPager(vp);

            for (int i = 0; i < enterpriseEditEntity.size(); i++) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.item_tab_com_config_menu, null, false);
                mCompanyTab.getTabAt(i).setCustomView(view);
                TextView tv = mCompanyTab.getTabAt(i).getCustomView().findViewById(R.id.tv_tabItem);
                tv.setTag(i);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position= (int) v.getTag();
                        if (mCompanyTab.getSelectedTabPosition() != position){
                            mCompanyTab.getTabAt(position).select();
                            mFragments.get(indexSelect).setNextTab(0);
                        }
                    }
                });
                String text = enterpriseEditEntity.get(i).getName();
                if (TextUtils.isEmpty(text)) return;
                SpannableString spannableString = new SpannableString(text);
                //设置字体大小（相对值,单位：像素） 参数表示为默认字体宽度的多少倍
                //2.0f表示默认字体宽度的两倍，即X轴方向放大为默认字体的两倍，而高度不变
                spannableString.setSpan(new ScaleXSpan(1.3f), 0, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(spannableString);
                if (i == 0) {
                    tv.setSelected(true);
                }
            }
            mCompanyTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    TextView tv = tab.getCustomView().findViewById(R.id.tv_tabItem);
                    tv.setSelected(true);
                    tv.setTag(mCompanyTab.getSelectedTabPosition());
                    tv.invalidate();
                    if (isAotu) { // 当是自动滚动的时候
                        if (indexSelect != mCompanyTab.getSelectedTabPosition()) {
                            indexSelect = mCompanyTab.getSelectedTabPosition();
                            startTimer();
                        }
                    } else { //当是用户手动滑动的时候
                        indexSelect = mCompanyTab.getSelectedTabPosition();
                        startTimer();
                    }
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                    TextView tv = tab.getCustomView().findViewById(R.id.tv_tabItem);
                    tv.setSelected(false);
                    tv.invalidate();
                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });
        }catch (Exception e){
            Log.e("initdata",e.toString());
        }
    }

    public void setIsAotu(boolean aotuTab, boolean aotuContext) {
        isInIt = true;
        this.aotuTab = aotuTab;
        this.aotuContext = aotuContext;
        isAotu = true;
        startTimer();
    }

    /**
     * 开始定时执行
     */
    public void startTimer() {
        stopTimer();
        // 每隔loadingTime毫秒执行一次逻辑代码
        disposable = Observable.interval(loadingTime, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@NonNull Long aLong) {
                        if (inflatedCompany.getVisibility() == View.VISIBLE) {
                            MLog.d("时间到 startTimer  是否手动滑动 = " + iscontinue + "  是否自动 == " + isAotu);
                            if (!iscontinue) return;
                            if (!isAotu) return; //当不是自动滚，刚好时间到了，阻断往下执行
                            MLog.d("时间到 执行切换");
                            // 逻辑代码
                            setCompanyTabSelect();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    /**
     * 根据设定的循环滚动方式来开始滚动
     */
    private void setCompanyTabSelect() {
        try {
            isAotu = true;
            aotuTab = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsType, true);
            aotuContext = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.DisplaySettingsQY, true);
            MLog.d("时间到 切换方式 aotuTab=" + aotuTab + "  aotuContext = " + aotuContext);
            // tab自动 内容也自动
            if (aotuTab && aotuContext) {
                if (mFragments.get(indexSelect).setNextTab()) {
                    MLog.d("时间到 执行tab切换  全部自动切换");
                    setAotuTab();
                }
            } else if (aotuTab && !aotuContext) {
                MLog.d("时间到 执行tab切换 tyep自动切换，内容不自动");
                setAotuTab();
            } else if (!aotuTab && aotuContext) {
                MLog.d("时间到 执行tab切换 tyep不自动切换，内容自动");
                if (mFragments.get(indexSelect).setNextTab()) {
                    mFragments.get(indexSelect).setNextTab(0);
                    startTimer();
                }
            } else {
                MLog.d("时间到 两者都不自动切换");
                stopTimer();
            }
        } catch (Exception e) {
            MLog.d("时间到  " + e.toString());
        }
    }

    private void setAotuTab() {
        indexSelect++;
        if (indexSelect == mFragments.size()) {
            indexSelect = 0;
        }
        mCompanyTab.getTabAt(indexSelect).select();
        mFragments.get(indexSelect).setNextTab(0);
    }

    /**
     * 停止定时执行
     */
    public void stopTimer() {
        if (null != disposable) {
            disposable.dispose();
            disposable = null;
        }
    }

    /**
     * 分页数据从自动变成用户滑动时的， 按下和抬起
     *
     * @param iscontinue
     */
    private void setTimeType(boolean iscontinue) {
        this.iscontinue = iscontinue;
        if (iscontinue) {
            indexSelect = mCompanyTab.getSelectedTabPosition();
            isAotu = true;
            startTimer(); // 手指抬起时，重新开始计时器
        } else {
            isAotu = false;
            stopTimer(); // 手指按下时，停止计时器
        }
    }


    private class MyPagerAdapter extends FragmentStatePagerAdapter {
        List<EnterpriseEditEntity> enterpriseEditEntity;
        ArrayList<SimpleCardFragment> mFragments;
        private int mChildCount = 0;

        public MyPagerAdapter(FragmentManager fm, ArrayList<SimpleCardFragment> mFragments, List<EnterpriseEditEntity> enterpriseEditEntity) {
            super(fm);
            this.enterpriseEditEntity = enterpriseEditEntity;
            this.mFragments = mFragments;
        }

        @Override
        public int getCount() {
            return enterpriseEditEntity.size();
        }

        @Override
        public String getPageTitle(int position) {
            String name = "";
            if (enterpriseEditEntity.size() == 0){
                name = "成员";
            }else{
                name = enterpriseEditEntity.get(position).getName();
            }
            return name;
        }

        @Override
        public SimpleCardFragment getItem(int position) {
            SimpleCardFragment fragment;
            try{
                fragment = mFragments.get(position);
            }catch (Exception e){
                fragment = SimpleCardFragment.getInstance(new EnterpriseEditEntity(new ArrayList<>()),mutableLiveData);
            }
            return fragment;
        }

        @Override
        public void notifyDataSetChanged() {
            // 重写这个方法，取到子Fragment的数量，用于下面的判断，以执行多少次刷新
            mChildCount = getCount();
            super.notifyDataSetChanged();
        }

        @Override
        public int getItemPosition(Object object) {
            if (mChildCount > 0) {
                // 这里利用判断执行若干次不缓存，刷新
                mChildCount--;
                // 返回这个是强制ViewPager不缓存，每次滑动都刷新视图
                return POSITION_NONE;
            }
            // 这个则是缓存不刷新视图
            return super.getItemPosition(object);
        }

    }

    private void showCompanyConfigWindow() {
        if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, "").equals("")) {
            EventBus.getDefault().postSticky("transport_to_login");
        } else {
            int TYPE = SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0);
            if (TYPE == 0) {
                boolean isAuth = SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, false);
                if (!isAuth) {
                    ACAdminDialogUtils.showACDialog(ACAdminDialogUtils.TYPE_AUTH_NO_NEW_AC, mContext);
                    return;
                }
            }
            ActivityJump.startActivity(AppRouteConstant.EnterpriseConfigActivity);
        }
    }

}
